﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YiNing.UI.Controls;
using YiNing.UI.Forms;

namespace YiNing.Tools
{
    public partial class NonstandardMappingTool : Form
    {
        [DllImport("user32")]
        private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
        private const int WM_SETREDRAW = 0xB;
        /// <summary>
        /// 重写CreateParams方法
        /// 解决控件过多加载闪烁问题
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;//用双缓冲绘制窗口的所有子控件
                return cp;
            }
        }

        string saveFileName = "";
        public NonstandardMappingTool()
        {
            InitializeComponent();
            propertyGrid1.PropertyValueChanged += PropertyGrid1_PropertyValueChanged;
            //nonstandardWafermap1.Notchlocation = 90;
            nonstandardWafermap1.OnDieClick += NonstandardWafermap1_OnDieClick;
        }

        private void PropertyGrid1_PropertyValueChanged(object s, PropertyValueChangedEventArgs e)
        {
            if (nonstandardWafermap1.SelectOneDie.Id != "")
            {
                var one = nonstandardWafermap1.Dataset.FindAll(v => v.Id == nonstandardWafermap1.SelectOneDie.Id);
                if (one != null && one.Count > 1)
                {
                    nonstandardWafermap1.SelectOneDie.Id = "";
                    propertyGrid1.SelectedObject = nonstandardWafermap1.SelectOneDie;
                    DarkMessageBox.ShowError("标识已存在，请重新输入");
                    return;
                }
            }
            JsonHelper.Serialize(nonstandardWafermap1.Dataset, saveFileName);
        }

        private List<Die> trainDies = new List<Die>();
        private void NonstandardWafermap1_OnDieClick(object sender, Die e)
        {
            Control c = (Control)sender;

            propertyGrid1.SelectedObject = e;
            //MessageBox.Show(c.Tag.ToString());
            //if (trainDies.Find(v => v.XPluse == e.XPluse && v.YPluse == e.YPluse) == null)
            //{
            //    e.ColorIndex = 2;
            //    trainDies.Add(e);
            //}
            //else
            //{
            //    e.ColorIndex = 1;
            //    trainDies.Remove(e);
            //}
            //this.Text = trainDies.Count.ToString();

            //YiningImage yiningImage = new YiningImage(300000, 300000);

            //yiningImage.DrawCircle(nonstandardWafermap1.WaferMinX, nonstandardWafermap1.WaferMaxY, nonstandardWafermap1.WaferRadius * 2, nonstandardWafermap1.WaferRadius * 2);


            //Point lt = e.GetDieRectLeftTopPoint(true, 1, 1, 7808, 9400);
            //Point rb = e.GetDieRectRightBottomPoint(true, 1, 1, 7808, 9400);

            //Point lb = new Point(Convert.ToInt32(e.GetDieRectLeftBottomPoint(true, 1, 1, 7808, 9400).X + nonstandardWafermap1.WaferMinX),Convert.ToInt32(e.GetDieRectLeftBottomPoint(true, 1, 1, 7808, 9400).Y + nonstandardWafermap1.WaferMinY));
            //Point rt = new Point(Convert.ToInt32(e.GetDieRectRightTopPoint(true, 1, 1, 7808, 9400).X + nonstandardWafermap1.WaferMinX), Convert.ToInt32(e.GetDieRectRightTopPoint(true, 1, 1, 7808, 9400).Y + nonstandardWafermap1.WaferMinY));
            //yiningImage.DrawRectleByLeftBottomAndRightTop(lb, rt);
            //yiningImage.Save(@"D:\QTWaferProgram\384\test\1.jpg");
            //yiningImage.DrawRectleByLeftTopAndRightBottom(lt, rb, new Pen(Color.Green, 10));
            //yiningImage.Save(@"D:\QTWaferProgram\384\test\2.jpg");

        }

        private void loadMappingProgram()
        {
            string filePath2;
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            folderBrowser.RootFolder = Environment.SpecialFolder.MyComputer; //
            folderBrowser.SelectedPath = @"D:\QTWaferProgram";
            folderBrowser.Description = "请选择程式文件夹";
            //folderBrowser.ShowNewFolderButton = true;
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                string conf = Path.Combine(folderBrowser.SelectedPath, "config.zyn");
                if (!File.Exists(conf)) {
                    DarkMessageBox.ShowError("当前选择的目录不存在程式，请重新选择");
                    return;
                }
                var programConfig = JsonHelper.DeserializeByFile<TestProgramConfig>(conf);
                if (!programConfig.IsNonstandardMapping)
                {
                    DarkMessageBox.ShowError("当前选择的程式是标准的图谱，请重新选择");
                    return;
                }
                nonstandardWafermap1.SetWaferInfo(programConfig.WaferCenter, programConfig.WaferRadius);

                string mappingFileName = Path.Combine(folderBrowser.SelectedPath, "nonstandardMapping.zyn");
                if (!File.Exists(mappingFileName))
                {
                    DarkMessageBox.ShowError("程式图谱丢失，请重新选择");
                    return;
                }
                saveFileName = mappingFileName;
                File.Copy(mappingFileName, mappingFileName + ".bak", true);
                var data = JsonHelper.DeserializeByFile<List<Die>>(mappingFileName);
                foreach(var one in data)
                {
                    one.ProgramName = programConfig.Name;
                }
                //nonstandardWafermap1.Colors = Die.DefaultColors;

                //var data = JsonHelper.DeserializeByFile<List<Die>>(@"D:\QTWaferProgram\test\result_mapping.txt");
                nonstandardWafermap1.Dataset = data;//JsonHelper.DeserializeByFile<List<Die>>(@"C:\Users\Administrator\Downloads\384\nonstandardMapping.zyn");
                nonstandardWafermap1.Notchlocation = 90;
                //lbAllDiesNum.Text = waferMap.DieAllNum.ToString();
                //lbOkDiesNum.Text = waferMap.DieOkNum.ToString();
                //lbNgDiesNum.Text = waferMap.DieNgNum.ToString();
                nonstandardWafermap1.BringToFront();
                //waferMap.Dataset = data;
                //waferMap.Notchlocation = 90;
                ////wmap.MinimumSize = new Size(500, 500);
                //waferMap.Interactive = true;
                nonstandardWafermap1.NotcheOrFlat = UI.Config.Enums.TraitType.Notch;
            }
        }

        public void range()
        {
            List<Die> dies = new List<Die>();
            foreach (var die in nonstandardWafermap1.Dataset)
            {
                //die.OffsetWaferCenterYPulse -= 9720 / 2;
                //die.YPluse -= 9720 / 2;
                //dies.Add(die);
                ////Size dieSize = die.GetDieSize();

                ////if (dieSize.Width>8500)
                ////{
                ////    dies.Add(die);
                ////}
            }

            JsonHelper.Serialize(dies, @"D:\QTWaferProgram\384\big-----a.zyn");
        }
        private void Button_Click(object sender, EventArgs e)
        {
            DarkButton btn = sender as DarkButton;
            string type = btn.Text.ToString();
            switch (type)
            {
                case "加载程式图谱":
                    loadMappingProgram();
                    break;

                case "保存程式图谱":
                    JsonHelper.Serialize(nonstandardWafermap1.Dataset, saveFileName);
                    break;

            }
        }
    }
}
